﻿using Microsoft.EntityFrameworkCore.Metadata.Internal;
using Microsoft.Extensions.Logging;
using Newtonsoft.Json;
using PMS.SANY.Entity;
using PMS.SANY.MonOrderServer.Models;
using PMS.SANY.MonOrderServer.Utils;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace PMS.SANY.MonOrderServer
{
    public partial class WorkStation
    {
        private static string ip = "10.28.0.182:8056";
        private string baseUrl = string.Format("http://" + ip + "/SANY/gateway/pdev/sany/slaveId/task/report");

        /// <summary>
        /// 中控系统代号
        /// </summary>
        private string reqSys = "JBTHJXZK001";

        /// <summary>
        /// 工厂编号
        /// </summary>
        private string Facility = "3505";

        public async Task MonReportAsync(string ProgressType)
        {
            var data = BuildHeader(ProgressType);
            var model = (MonProductionStatus)data.reported;
            decimal num;
          
            StationExecuted entity = new StationExecuted()
            {
                ActualCompleteDate = model.ActualCompleteDate,
                ActualStartDate = model.ActualStartDate,
                CreateTime = DateTime.Now,
                CreateUserId = "1",
                Deleted = false,
                DeviceID = model.DeviceID,
                EmployeeNo = model.EmployeeNo,
                Facility = model.Facility,
                Id = data.taskId,
                ModifyTime = DateTime.Now,
                ModifyUserId = "1",
                NGQuantity = model.NGQuantity,
                OprSequenceNo = model.OprSequenceNo,
                paramRsrv1 = model.paramRsrv1,
                paramRsrv2 = model.paramRsrv2,
                paramRsrv3 = model.paramRsrv3,
                paramRsrv4 = model.paramRsrv4,
                paramRsrv5 = model.paramRsrv5,
                PlanId = OprSequenceId,
                ProductNo = model.ProductNo,
                ProgressType = model.ProgressType,
                Quantity = model.Quantity,
                reqId = model.reqId,
                reqSys = model.reqSys,
                SequenceId = OprSequenceId,
                SequenceNo = model.SequenceNo,
                SerialNo = model.SerialNo,
                WipOrderNo = model.WipOrderNo,
                Status = StationExecutedStatus.Succeed

            };
            bool result = false;
            try
            {
                var idx = 0;

                if (!string.IsNullOrWhiteSpace(model.WipOrderNo))
                {
                    result = SendDataToMon(data);
                    while (!result && idx < 1)
                    {
                        idx += 1;
                        await Task.Delay(1000 * 10);

                        data.taskId = Guid.NewGuid().ToString("n");
                        result = SendDataToMon(data);
                    }
                }
                else
                {
                    _logger.LogError("MonReportAsync WipOrderNo IsNullOrWhiteSpace：" + JsonConvert.SerializeObject(data));
                }
            }
            catch(Exception ex)
            {
                _logger.LogError("WorkStation.MonReportAsync Error" + ex.Message);
            }

            if (!result) entity.Status = StationExecutedStatus.Fail;

            try
            {
                await AddStationExecuted(entity);
            }
            catch(Exception ex)
            {
                _logger.LogError("WorkStation.Save StationExecuted Error" + ex.Message);
            }
        }

        private bool SendDataToMon(MonReportHeader data)
        {
            var jsondata = JsonConvert.SerializeObject(data);
            _logger.LogWarning("生产进度反馈接口上传数据" + jsondata);
            try
            {
                var response = HttpPostHelper.HttpPost(baseUrl, jsondata);
                try
                {
                    _logger.LogWarning("生产进度反馈接口调用成功,返回数据：" + response);
                    var result = JsonConvert.DeserializeObject<MonReturnData>(response);
                    if (result.code != "0")
                    {
                        _logger.LogError(result.msg);
                    }
                }
                catch
                {
                }

                return true;
            }
            catch (Exception ex)
            {
                _logger.LogError("生产进度反馈接口调用成功,返回数据：" + ex.Message);
                return false;
            }
        }

        private MonReportHeader BuildHeader(string ProgressType)
        {
            MonReportHeader header = new MonReportHeader();
            header.version = 1;
            header.taskId = Guid.NewGuid().ToString("n");
            header.taskType = "3";
            header.reported = BuildStatus(ProgressType);

            return header;
        }

        private MonProductionStatus BuildStatus(string ProgressType)
        {
            MonProductionStatus model = new MonProductionStatus();

            model.reqId = string.Format("{0}{1}{2}", reqSys
                , DateTime.Now.ToString("yyyyMMdd")
                , Siemens.GetNextOrderId().ToString().PadLeft(6, '0'));

            model.reqSys = reqSys;
            model.Facility = Facility;
            model.WipOrderNo = WipOrderNo;
            model.SequenceNo = "000000";
            model.OprSequenceNo = OprSequenceNo;
            model.ProgressType = ProgressType;
            model.DeviceID = "";
            model.Quantity = 1;
            model.NGQuantity = 0;
            model.EmployeeNo = "00003505";
            model.ProductNo = ProductNo;
            model.paramRsrv1 = "";
            model.paramRsrv2 = Id;
            model.paramRsrv3 = "";
            model.paramRsrv4 = "";
            model.paramRsrv5 = "";
            model.SerialNo = "";
            model.ActualStartDate = "";
            model.ActualCompleteDate = "";


            if (Id == "3505CX01A0010" || Id == "3505CX01A0020")
            {
                model.Quantity = 4;
            }

            model.keyaccessoryList = new List<MonKayaccessory>() { };           



            if (ProgressType=="0")
            {//开工
                model.ActualStartDate = DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss");
            }
            else if (ProgressType == "1")
            {//完工
                model.ActualCompleteDate= DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss");
                if(SerialNo.Count()>= ActQuantity)
                {
                    model.SerialNo = SerialNo[ActQuantity - 1];
                }
                else
                {
                    model.SerialNo = "";
                }
            }

            return model;
        }
    }
}
